/*
 	Copyright 2012 Christian Brosch
    This file is part of EasyGPSTracker.

    EasyGPSTracker is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    EasyGPSTracker is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with EasyGPSTracker.  If not, see <http://www.gnu.org/licenses/>.
 */

package broware.easygpstracker;

import java.util.Comparator;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import broware.easygpstracker.R;

public class EGTActivity extends Activity {

	/*
	 * UI-Elements
	 */
	TextView statusmsg;
	ListView list_savedcomm;
	Button btn_send;
	EditText comment_edit;
	CheckBox save_cb;
	
	/*
	 * Activity
	 */
	   
	@Override
	public void onCreate(Bundle savedInstanceState) {
	       super.onCreate(savedInstanceState);
	       setContentView(R.layout.main);
	       serviceIntent = new Intent(getApplicationContext(),EGTService.class);
	       startService(serviceIntent);
	       statusmsg =  (TextView) findViewById(R.id.statustext);
	       btn_send = (Button) findViewById(R.id.send_btn);
	       comment_edit = (EditText) findViewById(R.id.comment_txt);
	       save_cb = (CheckBox) findViewById(R.id.cb_save);
	       list_savedcomm = (ListView) findViewById(R.id.list_comments);
	       registerForContextMenu(list_savedcomm);
	       loadComms();
	       setEventListener();
	       bindService(serviceIntent, mservice,  Context.BIND_AUTO_CREATE);
	}
	
	public void onDestroy(){
		super.onDestroy();
		unbindService(mservice);
	}
	   
	/*
	 * ServiceConnection
	 */
	Timer msg_timer = new Timer();
	Intent serviceIntent;
	boolean lt_conn=false;
	private EGTService ltservice;
    private ServiceConnection mservice = new ServiceConnection(){
	@Override
	public void onServiceConnected(ComponentName arg0, IBinder service) {
	   ltservice = ((EGTService.LocalBinder)service).getService();
	   msg_timer.schedule(msg_task, (long) 1000, (long) 1000);
	   lt_conn=true;
	}
	public void onServiceDisconnected(ComponentName name) {
		ltservice = null;
		msg_timer.cancel();
		lt_conn=false;
	}
   };
   
   /*
    * Status-Text
    */
   
   private final TimerTask msg_task = new TimerTask(){
	   public void run(){
		   runOnUiThread(new Runnable() {
			    public void run() {
			       statusmsg.setText(ltservice.mmsg);
			    }
			});
	   }
   };
   
   /*
    * Event-Listener
	*/
   
   public void setEventListener(){
	   btn_send.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				   String lcomm = comment_edit.getText().toString();
				   comment_edit.setText("");
				   ltservice.manuelUpdate("comm",lcomm);
				   if(save_cb.isChecked()){
					  commSaveEntry(lcomm);
					  save_cb.setChecked(false);
				   }
			   }
		    });
	   list_savedcomm.setOnItemClickListener(new OnItemClickListener() {
		   @Override
		   public void onItemClick(AdapterView<?> arg0, View arg1, int pos,	long id) {
			   if(lt_conn)
				   ltservice.manuelUpdate("comm", list_savedcomm.getItemAtPosition(pos).toString());
		   }
	   });
   }
   
   public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	   if (v.getId()==R.id.list_comments) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
		menu.setHeaderTitle(list_savedcomm.getItemAtPosition(info.position).toString());
		menu.add(Menu.NONE, 0, 0, "Senden");
		menu.add(Menu.NONE, 1, 1, "Löschen");
	   }
   }
   @Override
   public boolean onContextItemSelected(MenuItem item) {   
	   AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
	   int menuItemIndex = item.getItemId();
	   String entry = list_savedcomm.getItemAtPosition(info.position).toString();
	   switch(menuItemIndex){
	   case 0:
		   		ltservice.manuelUpdate("comm", entry);
	   			return true;
	   case 1:
		   		commDeleteEntry(entry);
		   		return true;
		default:
			return false;
	   }
   }
   
   
   /*
    * Kommentare speichern und aufrufen
    */
   ArrayAdapter<String> adapter;
   DbOpenHelper dbhelper = new DbOpenHelper(this);
   public class DbOpenHelper extends SQLiteOpenHelper {

	    private static final int DATABASE_VERSION = 2;
	    private static final String DATABASE_NAME="EGT";
	    private static final String COMMS_TABLE_NAME = "comms";
	    private static final String COMMS_TABLE_CREATE =
	                "CREATE TABLE " + COMMS_TABLE_NAME + " (id INTEGER PRIMARY KEY, comm VARCHAR(90));";
	    
	    DbOpenHelper(Context context) {
	        super(context, DATABASE_NAME, null, DATABASE_VERSION);
	    }

	    @Override
	    public void onCreate(SQLiteDatabase db) {
	        db.execSQL(COMMS_TABLE_CREATE);
	    }

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
		
		public void write(String string){
			 Log.i("","save "+string);
			SQLiteDatabase db= this.getWritableDatabase();
			db.execSQL("INSERT INTO "+COMMS_TABLE_NAME+ " (comm) VALUES ('"+string+"')");
		}
		
		public void delete(String entry){
			SQLiteDatabase db= this.getWritableDatabase();
			db.execSQL("DELETE FROM "+COMMS_TABLE_NAME+" WHERE comm='"+entry+"'");
		}
		
		public Cursor read(){
			SQLiteDatabase db= this.getWritableDatabase();
			String query = "SELECT comm FROM "+COMMS_TABLE_NAME+" ORDER BY id DESC";
			Cursor cur=db.rawQuery(query,new String [] {});
			Log.i("",(Integer.toString(cur.getColumnCount())));
			return cur;
		}
	}
 
   	
   public void loadComms(){
	   Cursor cur = dbhelper.read();
       cur.moveToFirst();
       adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
       while(cur.isAfterLast()==false){
    	   adapter.add(cur.getString(0));
    	   cur.moveToNext();
       }
       commSortAdapter();
       list_savedcomm.setAdapter(adapter);
   }
   
   private void commSaveEntry(final String entry) {
	  dbhelper.write(entry);
	  adapter.add(entry);
	  commSortAdapter();
	  adapter.notifyDataSetChanged();	  
	}
   
   private void commDeleteEntry(final String entry){
	   dbhelper.delete(entry);
	   adapter.remove(entry);
	   commSortAdapter();
	   adapter.notifyDataSetChanged();
   }
   
   private void commSortAdapter(){
	   adapter.sort(new Comparator<String>() {
			public int compare(String object1, String object2) {
				return object1.compareTo(object2);
			};
		});
   }
   
   /*
    * Options-Menue
    */
   
   public boolean onCreateOptionsMenu(Menu menu)
   {
   	getMenuInflater().inflate(R.menu.egtactivitymenu, menu);
   	return super.onCreateOptionsMenu(menu);
   }
   
   public boolean onOptionsItemSelected(MenuItem item)
   {
   	switch (item.getItemId())
   	{
   	case R.id.menu_settings:
   		Intent pi = new Intent(EGTActivity.this, EGTSetup.class);
   		startActivity(pi);
   		return true;
   	case R.id.menu_exit:
   		stopService(serviceIntent);
   		finish();
   		return true;
	default:
			return super.onOptionsItemSelected(item);
   	}
   }
}